import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'
// create an axios instance
const service = axios.create({
	baseURL: process.env.BASE_API, // api 的 base_url
	timeout: 15000 // request timeout
})
// request interceptor
service.interceptors.request.use(
	config => {
		// Do something before request is sent
		if (store.getters.token) {
			// 让每个请求携带token-- ['token']为自定义key 请根据实际情况自行修改
			config.headers['token'] = getToken()
		}
		return config
	},
	error => {
		// Do something with request error
		console.log(error) // for debug
		Promise.reject(error)
	}
)
// response interceptor
service.interceptors.response.use(
	res => {
		const data = res.data
		if (data.code !== 200) {
			Message({
				message: data.message,
				type: 'error',
				duration: 1 * 1000
			})
			return Promise.reject(data.message)
		} else {
			console.log(data)
			return data
		}
	}, error => {
		Message({
			message: error + '（请联系系统管理员）',
			type: 'error',
			duration: 1 * 1000
		})
		return Promise.reject(error)
	})
export default service
